<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog v-model="dialogVisible" title="选择产品" width="1000">
         <div class="dialog-content">
            <!-- 左侧产品列表 -->
            <div class="row-2">
               <div class="row-2-search">
                  <el-input placeholder="请输入关键字" suffix-icon="Search" v-model="search" @input="handleSearch" />
               </div>
               <div class="table-container">
                  <el-table ref="leftTableRef" :data="tableData || []" style="width: 100%" border
                     @selection-change="handleSelectionChange" :row-key="(row: Product) => row.id">
                     <el-table-column type="selection" width="55" />
                     <el-table-column label="产品名称" prop="name" width="auto">
                        <template #default="scope">{{ scope.row.name }}</template>
                     </el-table-column>
                     <el-table-column prop="suppliers" label="供应商" width="auto">
                        <template #default="scope">{{ scope.row.suppliers[0]?.name }}</template>
                     </el-table-column>
                     <el-table-column prop="price" label="单价(元)" show-overflow-tooltip width="auto" />
                     <el-table-column prop="measure_unit_name" label="单位" show-overflow-tooltip width="auto" />
                  </el-table>
               </div>
            </div>

            <!-- 右侧已选产品列表 -->
            <div class="row-3">
               <div class="row-head">
                  <div class="row-head-left">已选{{ rightCount }}项</div>
                  <div class="row-head-right" @click="clearAll" v-if="rightCount > 0">
                     清空
                  </div>
               </div>
               <div class="table-container">
                  <el-table :data="rightTableData" style="width: 100%">
                     <el-table-column prop="name" label="产品名称" width="auto" />
                     <el-table-column prop="suppliers" label="供应商" width="auto">
                        <template #default="scope">{{ scope.row.suppliers[0]?.name }}</template>
                     </el-table-column>
                     <el-table-column prop="price" label="单价(元)" width="auto" />
                     <el-table-column prop="measure_unit_name" label="单位" width="auto" />
                     <el-table-column label="操作" width="auto">
                        <template #default="scope">
                           <el-button type="danger" link @click="removeRow(scope.row)">移除</el-button>
                        </template>
                     </el-table-column>
                  </el-table>
               </div>
            </div>
         </div>

         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button color="#626aef" @click="submit">确认</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, defineEmits, defineProps } from "vue";
import api from "@/api/index.js";
import type { ElTable } from "element-plus";
import type { ProcurementItem } from "../procurementType.ts";
const search = ref<string>("");
const emit = defineEmits(["selectProducts"]);
const props = defineProps({
   purchaseOrderItem: {
      type: Array as PropType<ProcurementItem[]>,
      default: () => [],
   },
   supplierId: {
      type: Number,
      default: 0,
   },
});
const handleSearch = () => {
   getProductList();
};
interface Product {
   id: number;
   name: string;
   no: string;
   specification: string;
}
// 获取产品列表
const getProductList = async () => {
   const res = await api.publicFun.getProductList({
      keywords: search.value,
      // supplier_id: props.supplierId,
   });
   if (res.code === 200 && Array.isArray(res.data)) {
      tableData.value = res.data;
   } else {
      tableData.value = [];
   }
};
const tableData = ref<Product[]>([]);

// 使用唯一标识name作为选中项的key
const selectedKeys = ref<Set<number>>(new Set());
const leftTableRef = ref<InstanceType<typeof ElTable>>();

// 右侧表格数据：从tableData中过滤出选中的项
const rightTableData = computed(() => {
   return tableData.value.filter((item) => selectedKeys.value.has(item.id));
});

const rightCount = computed(() => selectedKeys.value.size);

// 处理左侧表格选中变化
function handleSelectionChange(selection: Product[]) {
   selectedKeys.value = new Set(selection.map((item) => item.id));
}

// 更新左侧表格选中状态
function updateLeftTableSelection() {
   nextTick(() => {
      const table = leftTableRef.value;
      if (!table) return;

      // 找到要取消选中的行
      tableData.value.forEach((row) => {
         if (selectedKeys.value.has(row.id)) {
            table.toggleRowSelection(row, true);
         } else {
            table.toggleRowSelection(row, false);
         }
      });
   });
}

// 移除单行
function removeRow(row: Product) {
   selectedKeys.value.delete(row.id);
   selectedKeys.value = new Set(selectedKeys.value); // 触发响应式更新
   nextTick(() => {
      const table = leftTableRef.value;
      if (!table) return;
      table.toggleRowSelection(row, false);
   });
}

// 清空所有
function clearAll() {
   selectedKeys.value.clear();
   selectedKeys.value = new Set(); // 触发响应式更新
   nextTick(() => {
      const table = leftTableRef.value;
      if (!table) return;
      table.clearSelection();
   });
}

// 打开弹窗
const dialogVisible = ref(false);
const fatherPrductData = ref<ProcurementItem[]>([]);
const openLoading = async () => {
   dialogVisible.value = true;
   fatherPrductData.value = props.purchaseOrderItem;
   search.value = "";

   // 先清除之前的选择状态
   selectedKeys.value.clear();

   await getProductList();

   // 检查父组件数据和表格数据的匹配，并自动勾选
   if (fatherPrductData.value && fatherPrductData.value.length > 0) {
      const matchingIds = new Set(fatherPrductData.value.map((item) => item.product_id ? item.product_id : item.id));
      selectedKeys.value = matchingIds;

      nextTick(() => {
         const table = leftTableRef.value;
         if (!table) return;

         // 先清除所有选择
         table.clearSelection();

         // 然后重新选择匹配的行
         tableData.value.forEach((row) => {
            if (matchingIds.has(row.id)) {
               table.toggleRowSelection(row, true);
            }
         });
      });
   } else {
      // 如果没有已选产品，确保清除所有选择
      nextTick(() => {
         const table = leftTableRef.value;
         if (table) {
            table.clearSelection();
         }
      });
   }
};
const submit = () => {
   console.log('SelectProducts 提交的产品:', rightTableData.value);
   console.log('选中的产品ID:', Array.from(selectedKeys.value));
   emit("selectProducts", rightTableData.value);
   dialogVisible.value = false;
};
defineExpose({ openLoading });
</script>

<style lang="scss" scoped>
.dialog-content {
   display: flex;
   height: 600px;
   flex-direction: row;
   gap: 10px;

   .row-1 {
      flex: 1;
      border: 1px solid #f0f0f0;

      .row-1-title {
         display: flex;
         justify-content: space-between;
         align-items: center;
         padding: 16px;
         width: 76%;
         border-bottom: 1px solid #f0f0f0;
         margin: 0 auto;
         color: #172b4d;
      }

      .row-1-content {
         padding: 10px;
         margin: 0 10px;

         &:hover {
            background: #edecff;
            cursor: pointer;
            color: #626aef;
         }
      }
   }

   .row-2 {
      flex: 2;
      border: 1px solid #f0f0f0;
      width: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .row-2-search {
         padding: 10px;
         width: 50%;
      }

      .table-container {
         flex: 1;
         overflow-y: auto;
         overflow-x: hidden;

         &::-webkit-scrollbar {
            width: 6px;
            height: 6px;
         }

         &::-webkit-scrollbar-thumb {
            border-radius: 3px;
            background: #ddd;
         }

         &::-webkit-scrollbar-track {
            border-radius: 3px;
            background: #f5f5f5;
         }

         .el-table {
            height: 100%;
         }
      }
   }

   .row-3 {
      flex: 2;
      border: 1px solid #f0f0f0;
      display: flex;
      flex-direction: column;
      max-height: 100%;
      .row-head {
         display: flex;
         justify-content: space-between;
         align-items: center;
         padding: 16px;

         .row-head-left {}

         .row-head-right {
            color: #766fff;
            cursor: pointer;
         }
      }
      .table-container {
         flex: 1;
         overflow-y: auto;
         min-height: 0;
         }
   }
}

::v-deep .el-dialog {
   --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
   padding: 10px 16px;
   border-bottom: 1px solid #f0f0f0;
   font-weight: bold;
}

::v-deep .dialog-footer {
   padding: 10px 16px;
   border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
   color: #000;
}

::v-deep .el-dialog__body {
   padding: 20px 10px;
}

:deep(.cell) {
   white-space: nowrap;
   text-overflow: ellipsis;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
   background-color: #6860ff;
   border-color: #6860ff;
}

:deep(.el-checkbox__inner:hover) {
   border-color: #626aef !important;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
   background-color: #6860ff;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
   border-color: #6860ff;
}
</style>
